import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Tabs, Table, Tag, Button, Space, Statistic, Progress, Modal, Form, Input, Select, message, DatePicker, Timeline } from 'antd';
import { 
  CarOutlined, 
  EnvironmentOutlined, 
  DollarOutlined, 
  ClockCircleOutlined,
  CheckCircleOutlined,
  WarningOutlined,
  UserOutlined,
  CameraOutlined,
  BarChartOutlined,
  SettingOutlined,
  EnterOutlined,
  ExportOutlined,
  PayCircleOutlined
} from '@ant-design/icons';

const { TabPane } = Tabs;
const { Option } = Select;
const { RangePicker } = DatePicker;

// 停车记录数据接口
interface ParkingRecord {
  id: string;
  plateNumber: string;
  vehicleType: 'car' | 'truck' | 'motorcycle' | 'electric';
  entryTime: string;
  exitTime?: string;
  duration?: number;
  parkingSpace: string;
  zone: string;
  status: 'parked' | 'exited' | 'overdue' | 'paid';
  fee: number;
  paymentMethod?: 'cash' | 'card' | 'mobile' | 'monthly';
  paymentTime?: string;
  authMethod: 'card' | 'plate' | 'manual' | 'visitor';
  operator?: string;
}

// 停车位数据接口
interface ParkingSpace {
  id: string;
  number: string;
  zone: string;
  floor: string;
  type: 'standard' | 'compact' | 'disabled' | 'electric' | 'vip';
  status: 'occupied' | 'available' | 'reserved' | 'maintenance';
  vehicle?: {
    plateNumber: string;
    entryTime: string;
  };
  rate: number; // 每小时费率
}

// 模拟停车记录数据
const mockParkingRecords: ParkingRecord[] = [
  {
    id: 'P001',
    plateNumber: '粤B12345',
    vehicleType: 'car',
    entryTime: '2024-02-15 08:30:00',
    exitTime: '2024-02-15 18:45:00',
    duration: 615, // 分钟
    parkingSpace: 'A-101',
    zone: 'A区',
    status: 'exited',
    fee: 25.0,
    paymentMethod: 'mobile',
    paymentTime: '2024-02-15 18:40:00',
    authMethod: 'plate',
  },
  {
    id: 'P002',
    plateNumber: '粤B67890',
    vehicleType: 'car',
    entryTime: '2024-02-15 09:15:00',
    parkingSpace: 'B-205',
    zone: 'B区',
    status: 'parked',
    fee: 0,
    authMethod: 'card',
  },
  {
    id: 'P003',
    plateNumber: '粤B11111',
    vehicleType: 'electric',
    entryTime: '2024-02-15 07:45:00',
    exitTime: '2024-02-15 19:30:00',
    duration: 705,
    parkingSpace: 'E-001',
    zone: '电动车区',
    status: 'exited',
    fee: 30.0,
    paymentMethod: 'card',
    paymentTime: '2024-02-15 19:25:00',
    authMethod: 'card',
  },
  {
    id: 'P004',
    plateNumber: '粤B22222',
    vehicleType: 'car',
    entryTime: '2024-02-14 22:30:00',
    parkingSpace: 'C-301',
    zone: 'C区',
    status: 'overdue',
    fee: 45.0,
    authMethod: 'visitor',
    operator: '张三',
  }
];

// 模拟停车位数据
const mockParkingSpaces: ParkingSpace[] = [
  { id: 'A101', number: 'A-101', zone: 'A区', floor: '1F', type: 'standard', status: 'available', rate: 5 },
  { id: 'A102', number: 'A-102', zone: 'A区', floor: '1F', type: 'standard', status: 'occupied', 
    vehicle: { plateNumber: '粤B67890', entryTime: '2024-02-15 09:15:00' }, rate: 5 },
  { id: 'B205', number: 'B-205', zone: 'B区', floor: '2F', type: 'compact', status: 'occupied',
    vehicle: { plateNumber: '粤B67890', entryTime: '2024-02-15 09:15:00' }, rate: 4 },
  { id: 'E001', number: 'E-001', zone: '电动车区', floor: '1F', type: 'electric', status: 'available', rate: 6 },
  { id: 'V001', number: 'V-001', zone: 'VIP区', floor: '1F', type: 'vip', status: 'reserved', rate: 10 },
  { id: 'D001', number: 'D-001', zone: 'A区', floor: '1F', type: 'disabled', status: 'available', rate: 3 },
];

const ParkingSystem: React.FC = () => {
  const [records, setRecords] = useState<ParkingRecord[]>(mockParkingRecords);
  const [spaces, setSpaces] = useState<ParkingSpace[]>(mockParkingSpaces);
  const [activeTab, setActiveTab] = useState('overview');
  const [selectedRecord, setSelectedRecord] = useState<ParkingRecord | null>(null);
  const [paymentModalVisible, setPaymentModalVisible] = useState(false);
  const [form] = Form.useForm();

  // 计算统计数据
  const getStatistics = () => {
    const totalSpaces = spaces.length;
    const occupiedSpaces = spaces.filter(s => s.status === 'occupied').length;
    const availableSpaces = spaces.filter(s => s.status === 'available').length;
    const reservedSpaces = spaces.filter(s => s.status === 'reserved').length;
    const occupancyRate = (occupiedSpaces / totalSpaces) * 100;
    
    const todayRecords = records.filter(r => r.entryTime.startsWith('2024-02-15'));
    const totalRevenue = records.filter(r => r.status === 'exited').reduce((sum, r) => sum + r.fee, 0);
    const avgDuration = records.filter(r => r.duration).reduce((sum, r) => sum + (r.duration || 0), 0) / records.filter(r => r.duration).length;
    
    return { 
      totalSpaces, 
      occupiedSpaces, 
      availableSpaces, 
      reservedSpaces, 
      occupancyRate, 
      todayRecords: todayRecords.length,
      totalRevenue,
      avgDuration: Math.round(avgDuration)
    };
  };

  const stats = getStatistics();

  // 获取状态配置
  const getStatusConfig = (status: string) => {
    const configs = {
      parked: { color: 'processing', icon: <CarOutlined />, text: '在场' },
      exited: { color: 'success', icon: <CheckCircleOutlined />, text: '已离场' },
      overdue: { color: 'error', icon: <WarningOutlined />, text: '超时' },
      paid: { color: 'success', icon: <PayCircleOutlined />, text: '已缴费' }
    };
    return configs[status as keyof typeof configs] || configs.parked;
  };

  // 获取车辆类型配置
  const getVehicleTypeConfig = (type: string) => {
    const configs = {
      car: { name: '小汽车', icon: <CarOutlined /> },
      truck: { name: '货车', icon: <CarOutlined /> },
      motorcycle: { name: '摩托车', icon: <CarOutlined /> },
      electric: { name: '电动车', icon: <CarOutlined /> }
    };
    return configs[type as keyof typeof configs] || { name: type, icon: <CarOutlined /> };
  };

  // 获取停车位状态配置
  const getSpaceStatusConfig = (status: string) => {
    const configs = {
      occupied: { color: 'error', text: '占用' },
      available: { color: 'success', text: '空闲' },
      reserved: { color: 'warning', text: '预约' },
      maintenance: { color: 'default', text: '维护' }
    };
    return configs[status as keyof typeof configs] || configs.available;
  };

  // 处理缴费
  const handlePayment = (record: ParkingRecord) => {
    setSelectedRecord(record);
    form.setFieldsValue({
      plateNumber: record.plateNumber,
      fee: record.fee,
      paymentMethod: 'mobile'
    });
    setPaymentModalVisible(true);
  };

  const handlePaymentSubmit = async () => {
    try {
      const values = await form.validateFields();
      if (selectedRecord) {
        const updatedRecords = records.map(record => {
          if (record.id === selectedRecord.id) {
            return {
              ...record,
              status: 'paid' as const,
              paymentMethod: values.paymentMethod,
              paymentTime: new Date().toISOString().slice(0, 19).replace('T', ' ')
            };
          }
          return record;
        });
        setRecords(updatedRecords);
        message.success('缴费成功');
        setPaymentModalVisible(false);
      }
    } catch (error) {
      console.error('缴费失败:', error);
    }
  };

  // 停车记录表格列配置
  const recordColumns = [
    {
      title: '车牌号',
      dataIndex: 'plateNumber',
      key: 'plateNumber',
      render: (text: string, record: ParkingRecord) => (
        <Space>
          {getVehicleTypeConfig(record.vehicleType).icon}
          <span style={{ fontWeight: 'bold' }}>{text}</span>
        </Space>
      )
    },
    {
      title: '车位',
      dataIndex: 'parkingSpace',
      key: 'parkingSpace'
    },
    {
      title: '区域',
      dataIndex: 'zone',
      key: 'zone'
    },
    {
      title: '入场时间',
      dataIndex: 'entryTime',
      key: 'entryTime'
    },
    {
      title: '出场时间',
      dataIndex: 'exitTime',
      key: 'exitTime',
      render: (text: string) => text || '-'
    },
    {
      title: '停车时长',
      dataIndex: 'duration',
      key: 'duration',
      render: (duration: number) => {
        if (!duration) return '-';
        const hours = Math.floor(duration / 60);
        const minutes = duration % 60;
        return `${hours}小时${minutes}分钟`;
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const config = getStatusConfig(status);
        return (
          <Tag color={config.color} icon={config.icon}>
            {config.text}
          </Tag>
        );
      }
    },
    {
      title: '费用',
      dataIndex: 'fee',
      key: 'fee',
      render: (fee: number) => `¥${fee.toFixed(2)}`
    },
    {
      title: '认证方式',
      dataIndex: 'authMethod',
      key: 'authMethod',
      render: (method: string) => {
        const methods = {
          card: '刷卡',
          plate: '车牌识别',
          manual: '人工放行',
          visitor: '访客登记'
        };
        return methods[method as keyof typeof methods] || method;
      }
    },
    {
      title: '操作',
      key: 'action',
      render: (record: ParkingRecord) => (
        <Space>
          {record.status === 'overdue' && (
            <Button 
              type="primary" 
              size="small" 
              icon={<PayCircleOutlined />}
              onClick={() => handlePayment(record)}
            >
              缴费
            </Button>
          )}
        </Space>
      )
    }
  ];

  // 停车位表格列配置
  const spaceColumns = [
    {
      title: '车位编号',
      dataIndex: 'number',
      key: 'number'
    },
    {
      title: '区域',
      dataIndex: 'zone',
      key: 'zone'
    },
    {
      title: '楼层',
      dataIndex: 'floor',
      key: 'floor'
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => {
        const types = {
          standard: '标准',
          compact: '紧凑',
          disabled: '无障碍',
          electric: '电动车',
          vip: 'VIP'
        };
        return types[type as keyof typeof types] || type;
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const config = getSpaceStatusConfig(status);
        return <Tag color={config.color}>{config.text}</Tag>;
      }
    },
    {
      title: '当前车辆',
      key: 'vehicle',
      render: (record: ParkingSpace) => {
        if (record.vehicle) {
          return (
            <div>
              <div>{record.vehicle.plateNumber}</div>
              <div style={{ fontSize: '12px', color: '#999' }}>
                {record.vehicle.entryTime}
              </div>
            </div>
          );
        }
        return '-';
      }
    },
    {
      title: '费率',
      dataIndex: 'rate',
      key: 'rate',
      render: (rate: number) => `¥${rate}/小时`
    }
  ];

  return (
    <div style={{ padding: '24px' }}>
      {/* 统计信息 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={3}>
          <Card>
            <Statistic
              title="总车位"
              value={stats.totalSpaces}
              prefix={<EnvironmentOutlined />}
            />
          </Card>
        </Col>
        <Col span={3}>
          <Card>
            <Statistic
              title="已占用"
              value={stats.occupiedSpaces}
              valueStyle={{ color: '#cf1322' }}
              prefix={<CarOutlined />}
            />
          </Card>
        </Col>
        <Col span={3}>
          <Card>
            <Statistic
              title="空闲"
              value={stats.availableSpaces}
              valueStyle={{ color: '#3f8600' }}
              prefix={<CheckCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={3}>
          <Card>
            <Statistic
              title="使用率"
              value={stats.occupancyRate}
              precision={1}
              suffix="%"
              valueStyle={{ color: stats.occupancyRate > 80 ? '#cf1322' : '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={3}>
          <Card>
            <Statistic
              title="今日进场"
              value={stats.todayRecords}
              prefix={<EnterOutlined />}
            />
          </Card>
        </Col>
        <Col span={3}>
          <Card>
            <Statistic
              title="今日收入"
              value={stats.totalRevenue}
              precision={2}
              prefix="¥"
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={3}>
          <Card>
            <Statistic
              title="平均停车时长"
              value={Math.floor(stats.avgDuration / 60)}
              suffix="小时"
              prefix={<ClockCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={3}>
          <Card>
            <Statistic
              title="超时车辆"
              value={records.filter(r => r.status === 'overdue').length}
              valueStyle={{ color: '#d48806' }}
              prefix={<WarningOutlined />}
            />
          </Card>
        </Col>
      </Row>

      {/* 主要内容 */}
      <Card>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="业务概览" key="overview">
            <Row gutter={16}>
              <Col span={12}>
                <Card title="停车位分布" size="small">
                  <div style={{ 
                    height: '300px', 
                    background: '#f0f2f5', 
                    display: 'flex', 
                    alignItems: 'center', 
                    justifyContent: 'center',
                    border: '1px dashed #d9d9d9',
                    borderRadius: '6px'
                  }}>
                    <div style={{ textAlign: 'center', color: '#999' }}>
                      <BarChartOutlined style={{ fontSize: '48px', marginBottom: '16px' }} />
                      <div>停车位分布图表</div>
                    </div>
                  </div>
                </Card>
              </Col>
              <Col span={12}>
                <Card title="收入统计" size="small">
                  <div style={{ 
                    height: '300px', 
                    background: '#f0f2f5', 
                    display: 'flex', 
                    alignItems: 'center', 
                    justifyContent: 'center',
                    border: '1px dashed #d9d9d9',
                    borderRadius: '6px'
                  }}>
                    <div style={{ textAlign: 'center', color: '#999' }}>
                      <DollarOutlined style={{ fontSize: '48px', marginBottom: '16px' }} />
                      <div>收入趋势图表</div>
                    </div>
                  </div>
                </Card>
              </Col>
            </Row>
            
            <Card title="最近进出记录" size="small" style={{ marginTop: '16px' }}>
              <Timeline>
                {records.slice(0, 5).map(record => (
                  <Timeline.Item 
                    key={record.id}
                    color={record.status === 'exited' ? 'green' : record.status === 'overdue' ? 'red' : 'blue'}
                  >
                    <div>
                      <strong>{record.plateNumber}</strong> 
                      {record.status === 'exited' ? ' 离场' : ' 入场'}
                      <div style={{ fontSize: '12px', color: '#999' }}>
                        {record.status === 'exited' ? record.exitTime : record.entryTime} | {record.parkingSpace}
                      </div>
                    </div>
                  </Timeline.Item>
                ))}
              </Timeline>
            </Card>
          </TabPane>
          
          <TabPane tab="电子地图" key="map">
            <div style={{ 
              height: '500px', 
              background: '#f0f2f5', 
              display: 'flex', 
              alignItems: 'center', 
              justifyContent: 'center',
              border: '1px dashed #d9d9d9',
              borderRadius: '6px'
            }}>
              <div style={{ textAlign: 'center', color: '#999' }}>
                <EnvironmentOutlined style={{ fontSize: '48px', marginBottom: '16px' }} />
                <div>停车场电子地图</div>
                <div style={{ fontSize: '12px', marginTop: '8px' }}>
                  显示各区域停车位分布和占用情况
                </div>
              </div>
            </div>
          </TabPane>
          
          <TabPane tab="停车记录" key="records">
            <Table
              columns={recordColumns}
              dataSource={records}
              rowKey="id"
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`
              }}
              scroll={{ x: 1200 }}
            />
          </TabPane>
          
          <TabPane tab="车位管理" key="spaces">
            <Table
              columns={spaceColumns}
              dataSource={spaces}
              rowKey="id"
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 个车位`
              }}
            />
          </TabPane>
        </Tabs>
      </Card>

      {/* 缴费模态框 */}
      <Modal
        title={`车辆缴费: ${selectedRecord?.plateNumber}`}
        open={paymentModalVisible}
        onOk={handlePaymentSubmit}
        onCancel={() => setPaymentModalVisible(false)}
        width={500}
      >
        {selectedRecord && (
          <Form form={form} layout="vertical">
            <Form.Item label="车牌号" name="plateNumber">
              <Input disabled />
            </Form.Item>
            <Form.Item
              label="应缴费用"
              name="fee"
              rules={[{ required: true, message: '请输入费用' }]}
            >
              <Input prefix="¥" suffix="元" type="number" />
            </Form.Item>
            <Form.Item
              label="支付方式"
              name="paymentMethod"
              rules={[{ required: true, message: '请选择支付方式' }]}
            >
              <Select placeholder="选择支付方式">
                <Option value="cash">现金</Option>
                <Option value="card">刷卡</Option>
                <Option value="mobile">移动支付</Option>
                <Option value="monthly">月卡</Option>
              </Select>
            </Form.Item>
            
            <Card title="停车信息" size="small" style={{ marginTop: '16px' }}>
              <Row gutter={16}>
                <Col span={12}>
                  <div><strong>入场时间:</strong></div>
                  <div>{selectedRecord.entryTime}</div>
                </Col>
                <Col span={12}>
                  <div><strong>停车位:</strong></div>
                  <div>{selectedRecord.parkingSpace}</div>
                </Col>
              </Row>
              <Row gutter={16} style={{ marginTop: '8px' }}>
                <Col span={12}>
                  <div><strong>停车时长:</strong></div>
                  <div>
                    {selectedRecord.duration ? 
                      `${Math.floor(selectedRecord.duration / 60)}小时${selectedRecord.duration % 60}分钟` : 
                      '计算中...'
                    }
                  </div>
                </Col>
                <Col span={12}>
                  <div><strong>区域:</strong></div>
                  <div>{selectedRecord.zone}</div>
                </Col>
              </Row>
            </Card>
          </Form>
        )}
      </Modal>
    </div>
  );
};

export default ParkingSystem;